import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:tender_flutter/constant/app_config.dart';
import 'package:tender_flutter/constant/app_constant.dart';
import 'package:tender_flutter/constant/theme_colors.dart';
import 'package:tender_flutter/dialog/normal_text_dialog.dart';
import 'package:tender_flutter/http/api_response.dart';
import 'package:tender_flutter/page/home/model/market_entity.dart';
import 'package:tender_flutter/page/person/api/api_person.dart';
import 'package:tender_flutter/page/person/item/my_market_cell.dart';
import 'package:tender_flutter/router/router.dart';
import 'package:tender_flutter/router/router_map.gr.dart';
import 'package:tender_flutter/style/font_style.dart';
import 'package:tender_flutter/utils/screen_adaper.dart';
import 'package:tender_flutter/utils/toast.dart';
import 'package:tender_flutter/widgets/animation_dialog.dart';
import 'package:tender_flutter/widgets/base_appbar.dart';
import 'package:tender_flutter/widgets/load_state_layout.dart';

/// 我发布的供需
class PersonMarketPage extends StatefulWidget {
  @override
  _PersonMarketPageState createState() => _PersonMarketPageState();
}

class _PersonMarketPageState extends State<PersonMarketPage> {
  /// 刷新组件
  RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  Future<ApiResponse<MarketEntity>> _listFuture;

  LoadState _loadState = LoadState.State_Loading;

  int page = AppConfig.page;

  int pageCount = AppConfig.pageCount;

  /// 列表数据
  List<MarketList> _dataLists = [];

  ///刷新数据
  Future _refresh() async {
    if (_refreshController.isRefresh) {
      page = 1;
    }
    if (_refreshController.isLoading) {
      page += 1;
    }

    setState(() {
      _listFuture = _getData();
    });
  }

  /// 获取数据
  Future<ApiResponse<MarketEntity>> _getData() async {
    var response = await ApiPerson.getMyMarket<MarketEntity>(
      type: 0,
      page: page,
      pageCount: pageCount,
    );
    return response;
  }

  /// 删除供需
  Future _deleteData(int position, int marketId) async {
    var response = await ApiPerson.deleteMarket(marketId: marketId);
    if (response.status == Status.SUCCESS) {
      ToastUtils.show("删除成功");
      setState(() {
        _dataLists.removeAt(position);
      });
    }
  }

  FutureBuilder<ApiResponse<MarketEntity>> _buildFutureBuilder() {
    return FutureBuilder(
        future: _listFuture,
        builder: (BuildContext context,
            AsyncSnapshot<ApiResponse<MarketEntity>> snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            if (snapshot.hasData) {
              MarketEntity entity = snapshot.data.result;
              if (snapshot.data.status == Status.SUCCESS) {
                List temps = entity.xList == null ? [] : entity.xList;
                page == AppConfig.page
                    ? _dataLists = temps
                    : _dataLists += temps;
                if (_dataLists.isEmpty) {
                  _loadState = LoadState.State_Empty;
                } else {
                  _loadState = LoadState.State_Success;
                }
              } else {
                _loadState = LoadState.State_Error;
              }
            } else if (snapshot.hasError) {
              _loadState = LoadState.State_Error;
            }

            /// 结束刷新，处理分页
            if (_dataLists.length % AppConfig.pageCount != 0) {
              _refreshController.loadNoData();
            } else {
              if (_refreshController.isLoading) {
                _refreshController.loadComplete();
              }
            }
            if (_refreshController.isRefresh) {
              _refreshController.refreshCompleted();
            }
          }

          return LoadStateLayout(
            state: _loadState,
            successWidget: _initList(),
          );
        });
  }

  @override
  void initState() {
    super.initState();
    _listFuture = _getData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ThemeColors.colorWhite,
      appBar: _initAppBar(),
      body: _buildFutureBuilder(),
    );
  }

  /// 导航
  Widget _initAppBar() {
    return BaseAppBar(
      context,
      Text("我的供需", style: FonStyle.navTextStyle()),
      backgroundColor: ThemeColors.colorWhite,
    );
  }

  /// 主体内容列表
  Widget _initList() {
    return SmartRefresher(
        controller: _refreshController,
        enablePullUp: true,
        enablePullDown: true,
        onRefresh: _refresh,
        onLoading: _refresh,
        child: ListView.separated(
          itemCount: _dataLists.length,
          itemBuilder: (BuildContext context, int index) {
            MarketList model = _dataLists[index];
            return MyMarketListCell(
                data: model,
                onTap: () {
                  LRouter.navigatorCtx(context).push(Routes.marketDetailPage,
                      queryParams: {"marketId": model.id.toString()});
                },
                deleteCallback: () async {
                  var result = await showAnimationDialog(
                      context: context,
                      transitionType: TransitionType.rotation,
                      builder: (context) {
                        return NormalTextDialog(
                          content: "确定删除此条供需信息？",
                        );
                      });
                  if (result == AppConstant.DIALOG_ACTION_CONFIRM) {
                    _deleteData(index, model.id);
                  }
                });
          },
          separatorBuilder: (BuildContext context, int index) {
            return Divider(
              height: ScreenAdapter.height(10),
              color: ThemeColors.colorType11,
            );
          },
        ));
  }
}
